package com.yang.consumer;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.yang.domain.entity.Message;
import com.yang.domain.entity.VoucherOrder;
import com.yang.service.IVoucherOrderService;
import com.yang.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Map;
import static com.yang.constants.RabbitMqConstants.*;



/**
 * <p>
 *  消息队列监听器
 * </p>
 *
 * @author yang
 * @since 2022-10-22
 */
@Component
@Slf4j
public class OrderListener {


    @Resource
    private IVoucherOrderService voucherOrderService;
    @Resource
    private MessageService messageService;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MESSAGE_QUEUE, durable = "true"),
            exchange = @Exchange(name = MESSAGE_EXCHANGE,type = "topic"),
            key = MESSAGE_ROUTING_KEY
    ))
    @RabbitHandler
    public void orderMessageConsumer(@Payload Message message, @Headers Map<String,Object> headers, Channel channel) {
        try {

            VoucherOrder voucherOrder = JSONUtil.toBean(message.getMessageBody(), VoucherOrder.class);

            boolean success = voucherOrderService.save(voucherOrder);

            if (!success){
                return;
            }

            messageService.delete(message.getId());

            // 发送回调信息
            Long delverTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
            channel.basicAck(delverTag,false);
        }catch (Exception e) {
            e.printStackTrace();
        }

    }

}
